package com.promise.jokerdream.task

import com.promise.jokerdream.task.base.ITask
import com.promise.jokerdream.task.base.TaskResult
import com.promise.jokerdream.task.base.TaskStatus
import com.promise.jokerdream.task.base.TaskType
import kotlinx.coroutines.*
import java.util.concurrent.ConcurrentHashMap
import java.util.UUID

/**
 * 任务组 - 管理一组相关的任务
 */
class TaskGroup(
    val groupId: String = UUID.randomUUID().toString(),
    val groupName: String
) {
    private val tasks = ConcurrentHashMap<String, ITask>()
    private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
    private var _status: TaskGroupStatus = TaskGroupStatus.IDLE
    
    /**
     * 任务组状态
     */
    val status: TaskGroupStatus
        get() = _status
    
    /**
     * 获取任务组中的所有任务
     */
    val allTasks: List<ITask>
        get() = tasks.values.toList()
    
    /**
     * 任务组是否为空
     */
    val isEmpty: Boolean
        get() = tasks.isEmpty()
    
    /**
     * 任务组大小
     */
    val size: Int
        get() = tasks.size
    
    /**
     * 添加任务到组中
     */
    fun addTask(task: ITask): Boolean {
        return if (tasks.containsKey(task.id)) {
            false
        } else {
            tasks[task.id] = task
            true
        }
    }
    
    /**
     * 从组中移除任务
     */
    fun removeTask(taskId: String): ITask? {
        val task = tasks[taskId]
        task?.cancel()
        return tasks.remove(taskId)
    }
    
    /**
     * 获取指定ID的任务
     */
    fun getTask(taskId: String): ITask? {
        return tasks[taskId]
    }
    
    /**
     * 根据类型获取任务
     */
    fun getTasksByType(taskType: TaskType): List<ITask> {
        return tasks.values.filter { it.taskType == taskType }
    }
    
    /**
     * 根据状态获取任务
     */
    fun getTasksByStatus(status: TaskStatus): List<ITask> {
        return tasks.values.filter { it.getStatus() == status }
    }
    
    /**
     * 执行组中的所有立即任务
     */
    suspend fun executeImmediateTasks(): List<TaskResult> {
        val immediateTasks = getTasksByType(TaskType.IMMEDIATE)
        _status = TaskGroupStatus.RUNNING
        
        return try {
            val results = withContext(scope.coroutineContext) {
                immediateTasks.map { task ->
                    async { task.execute() }
                }.awaitAll()
            }
            
            _status = if (results.all { it is TaskResult.Success }) {
                TaskGroupStatus.COMPLETED
            } else {
                TaskGroupStatus.FAILED
            }
            
            results
        } catch (e: Exception) {
            _status = TaskGroupStatus.FAILED
            listOf(TaskResult.Failure(e))
        }
    }
    
    /**
     * 启动组中的所有定时任务
     */
    fun startScheduledTasks(): List<String> {
        val scheduledTasks = getTasksByType(TaskType.SCHEDULED)
        _status = TaskGroupStatus.RUNNING
        
        val jobIds = mutableListOf<String>()
        
        scheduledTasks.forEach { task ->
            jobIds.add(task.id)
        }
        
        return jobIds
    }
    
    /**
     * 取消指定任务
     */
    fun cancelTask(taskId: String): Boolean {
        val task = tasks[taskId]
        return if (task != null) {
            task.cancel()
            true
        } else {
            false
        }
    }
    
    /**
     * 取消组中的所有任务
     */
    fun cancelAllTasks() {
        tasks.values.forEach { it.cancel() }
        _status = TaskGroupStatus.CANCELLED
    }
    
    /**
     * 重置组中的所有任务
     */
    fun resetAllTasks() {
        tasks.values.forEach { it.reset() }
        _status = TaskGroupStatus.IDLE
    }
    
    /**
     * 清理已完成和已取消的任务
     */
    fun cleanup() {
        val toRemove = tasks.values.filter { 
            it.getStatus() == TaskStatus.COMPLETED || it.getStatus() == TaskStatus.CANCELLED
        }
        toRemove.forEach { tasks.remove(it.id) }
    }
    
    /**
     * 获取任务组统计信息
     */
    fun getStats(): TaskGroupStats {
        val allTasks = tasks.values.toList()
        val successCount = allTasks.count { it.getStatus() == TaskStatus.COMPLETED }
        val failureCount = allTasks.count { 
            it.getStatus() == TaskStatus.FAILED || it.getStatus() == TaskStatus.CANCELLED
        }
        
        return TaskGroupStats(
            groupId = groupId,
            groupName = groupName,
            total = allTasks.size,
            success = successCount,
            failure = failureCount
        )
    }
    
    /**
     * 销毁任务组
     */
    fun destroy() {
        cancelAllTasks()
        tasks.clear()
        scope.cancel()
        _status = TaskGroupStatus.DESTROYED
    }
    
    /**
     * 等待所有任务完成
     */
    suspend fun awaitCompletion() {
        while (tasks.values.any { it.getStatus() == TaskStatus.RUNNING || it.getStatus() == TaskStatus.PENDING }) {
            delay(100) // 每100ms检查一次
        }
    }
}

/**
 * 任务组状态
 */
enum class TaskGroupStatus {
    /**
     * 空闲状态
     */
    IDLE,
    
    /**
     * 运行中
     */
    RUNNING,
    
    /**
     * 已完成
     */
    COMPLETED,
    
    /**
     * 已取消
     */
    CANCELLED,
    
    /**
     * 执行失败
     */
    FAILED,
    
    /**
     * 已销毁
     */
    DESTROYED
}

/**
 * 任务组统计信息
 */
data class TaskGroupStats(
    val groupId: String,
    val groupName: String,
    val total: Int,
    val success: Int,
    val failure: Int
)
